import {
  ProCard,
  ProFormGroup,
  ProFormInstance,
} from '@ant-design/pro-components';
import {
  ProForm,
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { history, useRequest } from 'umi';
import {
  message,
  Button,
  Card,
  Breadcrumb,
  Collapse,
  Upload,
  Descriptions,
  Space,
  Modal,
  Table,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { UploadProps } from 'antd';
import {
  PlusOutlined,
  UploadOutlined,
  FileSearchOutlined,
  InboxOutlined,
} from '@ant-design/icons';
import {
  getLabelAdapter,
  isPassAdapter,
  TitleAdapter,
} from '../../commons/Adapter';
import TbaleExplainMap from '@/components/TipsMap';
import moment from 'moment';
const { Panel } = Collapse;
const { Dragger } = Upload;

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const formRef = useRef<ProFormInstance>();
  const addPersonFrom = useRef<ProFormInstance>();
  const [paperId, setPaperId] = useState('');
  const [filedDisable, setFiledDisable] = useState({
    username: true,
    technicalGrade: true,
    technicalName: true,
    type: true,
  });
  const [proTableData, setProTableData] = useState([]);
  const [updateStatus, setUpdateStatus] = useState(false);
  const [newpath, setNewPath] = useState();

  const [modalDataSource, setModalDataSource] = useState([]); //modal的数据源
  const [selectKeys, setSelectKeys] = useState([]); //modal checkbox默认选中
  const [saveType, setSaveType] = useState(''); //modal 点击确认 调用新增、更新还是暂存接口

  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    accept: '.docx,.doc,.pdf,.xls',
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({
          annexPath: info?.file?.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败！`);
      }
    },
  };
  //根据ID查询论文详情
  const findPaperDetailById = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/achieveTrans/findAchieveTransDetailById',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        setProTableData(result.userCommonRelations);
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  //更新论文
  const updatePaper = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/achieveTrans/updateAchieveTrans',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        if (result.code === 200) {
          history.push('/LabAchievements/ScientificResearch/AchieveTransform');
        } else {
          message.error(result.msg);
        }
      },
      formatResult: (res) => res,
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  //新增论文
  const addPaper = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/achieveTrans/addAchieveTrans',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        if (result.code === 200) {
          history.push('/LabAchievements/ScientificResearch/AchieveTransform');
        } else {
          message.error(result.msg);
        }
      },
      formatResult: (res) => res,
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );
  //查找所有标签
  const getAllLabel = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getAllLabel',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        // history.push('/LabAchievements/ScientificResearch/Paper');
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      // manual: true,
    },
  );
  //添加标签
  const addLabelDetail = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/addLabelDetail',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        getAllLabel.run();
        message.success('添加成功');
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // formatResult: res => res
      manual: true,
    },
  );

  //获取所有方向/direction/findAllDirection
  const findAllDirection = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/direction/findAllDirection',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        // setProTableData(result.userCommonRelations);
      },
      formatResult: (res) => {
        let datatemp: any = [];
        res.data.map((item: any) => {
          let dataObj = {
            key: item.directionName,
            value: item.directionName,
          };
          datatemp.push(dataObj);
        });
        return datatemp;
      },
      // manual: true,
    },
  );
  //
  const addOrUpdatePaperTemp = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/achieveTrans/addOrUpdateAchieveTemp`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        history.push('/LabAchievements/ScientificResearch/AchieveTransform');
        console.log(result);
      },
      manual: true,
    },
  );
  //审核
  const updateStatusIpi = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //根据userList获取人员列表/user/getUserList
  const getUserList = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/user/getUserList',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (result) => {
        console.log(result);
        let resultTemp: any = [];
        result.map((item: any) => {
          resultTemp.push(item.webId);
        });
        console.log(resultTemp);
        setSelectKeys(resultTemp);
      },
    },
  );

  useEffect(() => {
    const paperIdTemp = history.location.pathname.replace(
      '/LabAchievements/ScientificResearch/AchieveTransform/',
      '',
    );
    setPaperId(paperIdTemp);
    if (paperIdTemp !== 'new') {
      findPaperDetailById.run({ id: paperIdTemp }).then((e) => {
        const { year, authors, ...formdata2 } = e;
        formRef.current?.setFieldsValue({
          year: year ? moment(year, 'YYYY') : null,
          authors: authors != 'null' && authors ? authors : null,
          ...formdata2,
        });
      });
    }
  }, []);

  // useEffect(()=>{
  //   getUserList?.data
  // },[])
  const [isModalVisible, setIsModalVisible] = useState(false);
  // const modalForm = useRef<ProFormInstance>();

  const showModal = (value: any) => {
    console.log(value);
    setModalDataSource(value);
    setIsModalVisible(true);
  };

  const handleOk = () => {
    let paramTemp: any = [];
    selectKeys.map((element: any) => {
      paramTemp.push(
        getUserList?.data.filter((item: any) => item.webId === element)[0],
      );
    });
    if (saveType === '暂存') {
      let formRefData: any = formRef.current?.getFieldsValue();
      addOrUpdatePaperTemp.run({
        ...formRefData,
        userCommonRelations: paramTemp,
        id: paperId === 'new' ? null : paperId,
      });
    }
    if (saveType === '新增') {
      let formRefData: any = formRef.current?.getFieldsValue();
      addPaper.run({
        ...formRefData,
        userCommonRelations: paramTemp,
      });
    }
    if (saveType === '更新') {
      let formRefData: any = formRef.current?.getFieldsValue();

      updatePaper
        .run({
          ...formRefData,
          id: paperId,
          userCommonRelations: paramTemp,
        })
        .then(() => {
          if (localStorage.getItem('isEdit') === '审核') {
            updateStatusIpi
              .run({
                tableName: 'ACHIEVE_TRANS',
                ids: [paperId],
                status: 2, //审核通过
                tab: '子方向视角',
              })
              .then(() => {
                history.goBack();
                message.success('操作成功');
              });
          }
        });
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <PageContainer
      header={{
        title: findPaperDetailById?.data?.message ? (
          <div style={{ fontSize: 18, textAlign: 'center', color: 'red' }}>
            拒绝原因：{findPaperDetailById?.data?.message}
          </div>
        ) : null, //'编辑成果转化',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>科学研究</Breadcrumb.Item>
            <Breadcrumb.Item>成果转化</Breadcrumb.Item>
            <Breadcrumb.Item>
              {TitleAdapter(
                paperId,
                localStorage.getItem('isEdit'),
                '成果转化',
              )}
            </Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      extra={
        <div>
          {localStorage.getItem('isEdit') === '审核' ? (
            <Space>
              <ModalForm
                title="拒绝"
                trigger={<Button key="2">返回成员修改</Button>}
                autoFocusFirstInput
                modalProps={{
                  onCancel: () => console.log('run'),
                  destroyOnClose: true,
                }}
                submitTimeout={2000}
                onFinish={async (values) => {
                  console.log(values);
                  updateStatusIpi
                    .run({
                      tableName: 'ACHIEVE_TRANS',
                      ids: [paperId],
                      status: 3, //拒绝
                      message: values.message,
                      tab: '子方向视角',
                    })
                    .then(() => {
                      // findPaperDetailById.run({ id: paperId }).then((e) => {
                      //   formRef.current?.setFieldsValue(e);
                      //   setNewPath(e?.annexPath);
                      // });
                      history.goBack();
                      message.success('操作成功');
                    });
                  return true;
                }}
                grid={true}
                initialValues={{ message: findPaperDetailById?.data?.message }}
              >
                <ProForm.Group>
                  <ProFormText
                    name="message"
                    label="拒绝原因"
                    placeholder="请输入拒绝原因"
                    colProps={{ span: 24 }}
                    rules={[{ required: true, message: '请输入拒绝原因' }]}
                  />
                </ProForm.Group>
              </ModalForm>

              <Button
                key="1"
                type="primary"
                onClick={() => {
                  let formRefData: any = formRef.current?.getFieldsValue();
                  if (!formRefData?.annexPath) {
                    message.warning('请上传材料！');
                  } else {
                    if (paperId === 'new') {
                      setSaveType('新增');
                    } else {
                      setSaveType('更新');
                    }
                    getUserList
                      .run({ userList: formRefData.authors })
                      .then((e) => {
                        showModal(e);
                      });
                  }
                }}
              >
                提交管理员审核
              </Button>
            </Space>
          ) : null}
        </div>
      }
      content={
        <>
          {localStorage.getItem('isEdit') === '查看' ? (
            <Card>
              <Descriptions title="基本信息" layout="horizontal" bordered>
                {localStorage.getItem('identity') === '管理员' ? (
                  <>
                    <Descriptions.Item
                      label="序号"
                      labelStyle={{ width: 140 }}
                      span={1}
                    >
                      {findPaperDetailById?.data?.seq}
                    </Descriptions.Item>
                    <Descriptions.Item
                      label="年度"
                      labelStyle={{ width: 140 }}
                      span={2}
                    >
                      {findPaperDetailById?.data?.year}
                    </Descriptions.Item>
                  </>
                ) : null}
                {/* <Descriptions.Item label="编号" labelStyle={{ width: 140 }}>
              {findPaperDetailById?.data?.achieveId}
            </Descriptions.Item> */}
                <Descriptions.Item label="成果名称" span={3}>
                  {findPaperDetailById?.data?.achieveName}
                </Descriptions.Item>
                {/* <Descriptions.Item label="转化类型" span={3}>
              {findPaperDetailById?.data?.achieveType}
            </Descriptions.Item> */}
                <Descriptions.Item label="完成人" span={3}>
                  {findPaperDetailById?.data?.authors}
                </Descriptions.Item>
                <Descriptions.Item label="转化企业">
                  {findPaperDetailById?.data?.transCompany}
                </Descriptions.Item>
                <Descriptions.Item label="经济效益/万元">
                  {findPaperDetailById?.data?.transMoney}
                </Descriptions.Item>
                <Descriptions.Item label="合同名称">
                  {findPaperDetailById?.data?.contractName}
                </Descriptions.Item>
                <Descriptions.Item label="合同编号">
                  {findPaperDetailById?.data?.contractId}
                </Descriptions.Item>
                <Descriptions.Item label="签约时间">
                  {findPaperDetailById?.data?.contractTime}
                </Descriptions.Item>
                {/* <Descriptions.Item label="所属研究方向">
              {findPaperDetailById?.data.researchDire}
            </Descriptions.Item> */}
                <Descriptions.Item
                  label="成果转化标签"
                  span={localStorage.getItem('identity') !== '管理员' ? 0 : 2}
                >
                  {getLabelAdapter(
                    getAllLabel?.data,
                    findPaperDetailById?.data?.labels,
                  )}
                </Descriptions.Item>
              </Descriptions>
            </Card>
          ) : (
            <ProForm
              onFinish={async (values) => {
                // await waitTime(2000);
                if (!values?.annexPath) {
                  message.warning('请上传材料！');
                } else {
                  if (paperId === 'new') {
                    setSaveType('新增');
                  } else {
                    setSaveType('更新');
                  }
                  getUserList.run({ userList: values.authors }).then((e) => {
                    showModal(e);
                  });
                }
              }}
              formRef={formRef}
              formKey="base-form-use-demo"
              autoFocusFirstInput
              submitter={{
                render: (props, dom) => (
                  <FooterToolbar>
                    {localStorage.getItem('isEdit') === '审核' ? null : (
                      <>
                        {paperId === 'new' ||
                        findPaperDetailById?.data?.isPass + '' === '-1' ? (
                          <Button
                            onClick={() => {
                              setSaveType('暂存');
                              let values = props.form?.getFieldsValue();
                              if (values.authors) {
                                getUserList
                                  .run({ userList: values.authors })
                                  .then((e) => {
                                    showModal(e);
                                  })
                                  .catch((e) => message.error('作者填写有误'));
                              } else {
                                addOrUpdatePaperTemp.run({
                                  ...values,
                                  userCommonRelations: proTableData,
                                  id: paperId === 'new' ? null : paperId,
                                });
                              }
                            }}
                          >
                            暂存
                          </Button>
                        ) : null}
                        <Button
                          type="primary"
                          onClick={() => {
                            formRef.current?.submit();
                          }}
                        >
                          提交
                        </Button>
                      </>
                    )}
                  </FooterToolbar>
                ),
              }}
              grid={true}
              rowProps={{
                gutter: 16,
              }}
            >
              <ProForm.Group>
                <ProForm.Group title={'基本信息'}>
                  <ProFormText
                    disabled
                    name="seq"
                    label="序号"
                    colProps={{ span: 4 }}
                    hidden={true}
                  />
                  <ProFormText
                    name="achieveName"
                    label="成果名称"
                    colProps={{
                      span: 6,
                    }}
                    rules={[{ required: true, message: '请输入' }]}
                  />
                  <ProFormText
                    name="authors"
                    label="所有完成人（学生姓名后标*，外单位人员名字后标#）"
                    placeholder="请输入完成人，以英文逗号分隔"
                    colProps={{
                      span: 6,
                    }}
                    rules={[{ required: true, message: '请输入' }]}
                  />
                  <ProFormSelect
                    name={'completeState'}
                    label={'完成情况'}
                    colProps={{ span: 3 }}
                    rules={[
                      {
                        required: localStorage.getItem('identity') === '管理员',
                        message: '请选择',
                      },
                    ]}
                    hidden={localStorage.getItem('identity') !== '管理员'}
                    options={[
                      {
                        value: '独立完成',
                        label: '独立完成',
                      },
                      {
                        value: '第一完成人(非独立完成)',
                        label: '第一完成人(非独立完成)',
                      },
                      {
                        value: '非第一完成人(非独立完成)',
                        label: '非第一完成人(非独立完成)',
                      },
                    ]}
                  />
                  {/* <ProFormText
                  name="achieveId"
                  label="编号"
                  colProps={{ span: 4 }}
                  disabled={updateStatus}
                /> */}
                </ProForm.Group>
                <ProForm.Group title="详细内容">
                  <ProFormDatePicker.Year
                    name="year"
                    label="年度"
                    colProps={{ span: 3 }}
                    hidden={localStorage.getItem('identity') !== '管理员'}
                  />
                  <ProFormText
                    name="transCompany"
                    label="转化企业"
                    placeholder="请输入转化企业"
                    colProps={{
                      span: 3,
                    }}
                    rules={[{ required: true, message: '请输入' }]}
                  />
                  <ProFormText
                    name="contractId"
                    label="合同编号"
                    placeholder="请输入合同编号"
                    colProps={{ span: 3 }}
                    disabled={updateStatus}
                    rules={[{ required: true, message: '请输入' }]}
                  />
                  <ProFormText
                    name="transMoney"
                    label="转化金额（万元）"
                    placeholder="请输入转化金额（万元）"
                    colProps={{ span: 3 }}
                    rules={[{ required: true, message: '请输入' }]}
                  />
                  <ProFormDatePicker
                    name="contractTime"
                    label="签约时间"
                    fieldProps={{
                      format: 'YY-MM-DD',
                    }}
                    placeholder="请选择签约时间"
                    colProps={{ span: 3 }}
                    rules={[{ required: true, message: '请输入' }]}
                  />
                  {/* <ProFormText
                    name="contractName"
                    label="合同名称"
                    placeholder="请输入合同名称"
                    colProps={{ span: 3 }}
                    disabled={updateStatus}
                    rules={[{ required: true, message: '请输入' }]}
                  />
                  <ProFormText
                    name="contractId"
                    label="合同编号"
                    placeholder="请输入合同编号"
                    colProps={{ span: 4 }}
                    disabled={updateStatus}
                    rules={[{ required: true, message: '请输入' }]}
                  /> */}
                  <ProFormSelect
                    name="researchDire"
                    label="研究方向"
                    colProps={{
                      span: 12,
                    }}
                    fieldProps={{
                      options: findAllDirection?.data || [],
                    }}
                    required
                    disabled
                    hidden={true}
                  />
                  {/* <ProFormText
                        name="achieveType"
                        label="转化类型"
                        colProps={{ span: 3 }}
                        disabled={updateStatus}
                        rules={[{ required: true, message: '请输入' }]}
                      /> */}
                </ProForm.Group>
                <ProForm.Group title="佐证材料">
                  <ProFormSelect
                    options={getAllLabel?.data}
                    // width={800}
                    mode="tags"
                    name="labels"
                    label="成果转化标签"
                    colProps={{ span: 12 }}
                    hidden={localStorage.getItem('identity') !== '管理员'}
                    disabled={updateStatus}
                    addonAfter={
                      <ModalForm<{
                        year: string;
                        labelName: string;
                      }>
                        title="新增标签"
                        trigger={<a>新增标签</a>}
                        autoFocusFirstInput
                        modalProps={{
                          onCancel: () => console.log('run'),
                        }}
                        submitTimeout={2000}
                        onFinish={async (values) => {
                          addLabelDetail.run(values);
                          return true;
                        }}
                      >
                        <ProForm.Group>
                          <ProFormDatePicker.Year
                            width="md"
                            name="year"
                            label="标签年份"
                            required
                            disabled={updateStatus}
                          />
                          <ProFormText
                            width="md"
                            name="labelName"
                            label="标签名称"
                            required
                            disabled={updateStatus}
                          />
                        </ProForm.Group>
                      </ModalForm>
                    }
                  />
                  <ProFormText
                    width="sm"
                    name="annexPath"
                    label="附件链接"
                    hidden
                    colProps={{ span: 4 }}
                  />
                </ProForm.Group>
                <ProFormText
                  name={'annexPath'}
                  label={'材料地址'}
                  placeholder="待审核"
                  hidden
                />
                <ModalForm
                  title="上传材料"
                  trigger={
                    <Button icon={<UploadOutlined />} type="link">
                      上传材料（上传盖章合同，以成果名称命名）
                    </Button>
                  }
                  autoFocusFirstInput
                  submitTimeout={2000}
                  onFinish={async (values) => true}
                >
                  {/* TbaleExplainMap['STANDARD'] 要修改 */}
                  <ProCard title={TbaleExplainMap['ACHIEVE_TRANS']}>
                    {/* 有小问题，需要修改成pro的dragger */}
                    <Dragger {...props} maxCount={1}>
                      <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                      </p>
                      <p className="ant-upload-text">
                        单击或拖动文件到此区域进行上传
                      </p>
                      <p className="ant-upload-hint">请上传一个文件</p>
                    </Dragger>
                  </ProCard>
                </ModalForm>
                {findPaperDetailById?.data?.annexPath == null ? (
                  <Button
                    icon={<FileSearchOutlined />}
                    type="link"
                    onClick={() => {
                      message.info('请上传材料');
                    }}
                  >
                    暂无附件
                  </Button>
                ) : (
                  <Button
                    type="link"
                    onClick={() => {
                      window.open(findPaperDetailById?.data?.annexPath);
                    }}
                    icon={<FileSearchOutlined />}
                  >
                    查看材料
                  </Button>
                )}
              </ProForm.Group>
            </ProForm>
          )}
        </>
      }
    >
      <Modal
        title="请确认人员！"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        forceRender
      >
        <Table
          size="small"
          pagination={{ hideOnSinglePage: true, pageSize: 10 }}
          rowKey={'webId'}
          rowSelection={{
            onChange: (selectedRowKeys: React.Key[]) => {
              setSelectKeys(selectedRowKeys);
            },
            selectedRowKeys: selectKeys,
          }}
          columns={[
            {
              title: '工号',
              dataIndex: 'username',
              key: 'username',
            },
            {
              title: '姓名',
              dataIndex: 'realName',
              key: 'realName',
            },
            {
              title: '人员类型',
              dataIndex: 'userType',
              key: 'userType',
            },
          ]}
          dataSource={modalDataSource}
        />
      </Modal>
    </PageContainer>
  );
};
